package services

import (
	"fmt"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql/db_main"

	"github.com/jinzhu/copier"
	"github.com/labstack/echo/v4"
	"longmen/server/pkg/common/api_models"
)

func (s *Service) GetNoticeList(uid, page, size int) ([]*api_models.GetNoticeListResp, int64, error) {
	list, err := db_main.GetNoticeList(echo.Map{"or": []interface{}{"user_id = ? or user_id = 0", uid}}, page, size)
	if err != nil {
		return nil, 0, err
	}
	var lastCreateTime int64
	noticeList := make([]*api_models.GetNoticeListResp, 0)
	for _, notice := range list {
		dest := &api_models.GetNoticeListResp{}
		err := copier.Copy(dest, notice)
		if err != nil {
			return nil, 0, err
		}
		dest.CreateTime = notice.CreatedAt.Unix()
		noticeList = append(noticeList, dest)
		if lastCreateTime < 1 {
			lastCreateTime = notice.CreatedAt.Unix()
		}
	}
	return noticeList, lastCreateTime, nil
}

func (s *Service) GetLastNotice(uid int) (*api_models.GetNoticeResp, error) {
	fName := "GetLastNotice"
	notice, err := db_main.GetNoticeProfile(uid)
	if err != nil {
		return nil, fmt.Errorf("%s%s", util.Convert(fName), err.Error())
	}
	if notice.ID > 0 {
		resp := &api_models.GetNoticeResp{}
		runes := []rune(notice.Content)
		i := 10
		if len(runes) < 10 {
			i = len(runes)
		}
		resp.Content = string(runes[0:i]) + "..."
		resp.CreateTime = notice.CreatedAt.Unix()
		return resp, err
	} else {
		return &api_models.GetNoticeResp{}, nil
	}
}
